import React, { useState, useEffect, useContext } from "react";
import { MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";
import { Layout, Menu, Breadcrumb } from "antd";
import { useNavigate, useLocation } from "react-router";

const { Header, Sider, Content } = Layout;
import { context } from "../components/AppProvider";
import useAppStore from "../store";
import "./Layouts.less";

const HeadUser = React.lazy(async () => {
  const head = await import("../components/head/HeadUser.jsx");
  return head;
});

const Layouts = ({ children }) => {
  // context.Provider中导出的数据
  const { menus } = useContext(context);
  // 同步改变数据zustand
  // 改变侧边栏
  const setActives = useAppStore((state) => state.setActive);
  //递归获取menu
  const findOpenKeys = (key) => {
    let result = [];
    const findInfo = (arr) => {
      arr.forEach((item) => {
        if (key.includes(item.key)) {
          result.push(item.key);
          if (item.children) {
            findInfo(item.children);
          }
        }
      });
    };
    findInfo(menus);
    return result;
  };

  /**
   * 获取当前选中的数据的所有的父节点
   */
  // 获取面包屑
  const findDeepPath = (keys) => {
    let result = []; //处理完所有的menu数据，成为一维数组
    const findInfo = (arr) => {
      arr.forEach((item) => {
        const { children, ...info } = item;
        result.push(info);
        if (children) {
          findInfo(children); //递归处理子节点
        }
      });
    };
    findInfo(menus);
    //筛选面包屑
    const temData = result.filter((data) => keys.includes(data.key));
    if (temData.length > 0) {
      return [...temData];
    }
    return [];
  };
  //判断路由，不存在就去404页面
  const menuPath = () => {
    let pathList = [];
    const findInfo = (arrData) => {
      arrData.forEach((item) => {
        const { children, key } = item;
        pathList.push(key);
        if (children) {
          findInfo(children);
        }
      });
    };
    findInfo(menus);
    return pathList;
  };

  const navigate = useNavigate();
  const [breadcrumbs, setBreadcrumbs] = useState([]);
  const { pathname } = useLocation();
  const [collapsed, setCollapsed] = useState(false);
  // 获取持久化的menu激活
  const openKeys = findOpenKeys(pathname);

  useEffect(() => {
    setBreadcrumbs(findDeepPath(pathname));
    //menuPath() menuPath().length > 0 判断是不是刷新页面，如果是刷新页面直接放行
    if (
      menuPath() &&
      menuPath().length > 0 &&
      menuPath().indexOf(pathname) === -1
    ) {
      //路由不存在，去404
      navigate("/404");
    } else {
      //路由存在，放行
      setBreadcrumbs(findDeepPath(pathname));
    }
  }, [pathname]);
  useEffect(() => {
    return () => {
      localStorage.removeItem("globalState");
      sessionStorage.removeItem("globalState");
    };
  }, []);

  return (
    <Layout style={{ width: "100vw", height: "100vh" }}>
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
        style={{ background: "#fff" }}
      >
        <Menu
          theme="light"
          mode="inline"
          defaultOpenKeys={[...openKeys]}
          defaultSelectedKeys={[...openKeys]}
          onClick={({ key }) => {
            // 处理左边的图标激活使用的是zustand
            setActives(key.split("/") && key.split("/")[2]);
            navigate(key);
          }}
          items={menus}
        />
      </Sider>
      <Layout className="site-layout">
        <Header
          className="site-layout-background"
          style={{
            padding: "0 40px 0 20px",
            display: "flex",
            justifyContent: "space-between",
          }}
        >
          {React.createElement(
            collapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
            {
              className: "trigger",
              onClick: () => setCollapsed(!collapsed),
            }
          )}
          <div>
            <HeadUser />
          </div>
        </Header>
        <Content
          className="site-layout-background"
          style={{
            margin: "24px 16px",
            minHeight: 280,
          }}
        >
          <Breadcrumb>
            {breadcrumbs &&
              breadcrumbs.map((item, index) => (
                <Breadcrumb.Item key={index}>{item.label}</Breadcrumb.Item>
              ))}
          </Breadcrumb>
          {/* <Outlet /> */}
          {children}
        </Content>
      </Layout>
    </Layout>
  );
};

export default Layouts;
